package redis

import (
	"cart_srv/cartsrv"
	"context"
	"fmt"
	"strconv"
)

func AddCart(userId, goodsId, num int, title, cover string, price float64) {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	Rdb.HMSet(context.Background(), key, map[string]interface{}{
		"goodsId":    goodsId,
		"goodsTitle": title,
		"goodsCover": cover,
		"goodsPrice": price,
		"goodsNum":   num,
		"checked":    1,
	})
}
func FindCart(userId, goodsId int) (num int, err error) {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	val, _ := Rdb.HGetAll(context.Background(), key).Result()
	num, _ = strconv.Atoi(val["goodsNum"])
	return
}
func ListCart(userId int) (carts []*cartsrv.ListCart, err error) {

	key := fmt.Sprintf("cart:user_id_%d:goods_id_*", userId)
	keys, err := Rdb.Keys(context.Background(), key).Result()
	for _, k := range keys {
		val := Rdb.HGetAll(context.Background(), k).Val()
		goodsId, _ := strconv.Atoi(val["goodsId"])
		goodsTitle := val["goodsTitle"]
		goodsCover := val["goodsCover"]
		goodsPrice, _ := strconv.Atoi(val["goodsPrice"])
		goodsNum, _ := strconv.Atoi(val["goodsNum"])
		checked, _ := strconv.Atoi(val["checked"])

		carts = append(carts, &cartsrv.ListCart{
			GoodsId:    int64(goodsId),
			GoodsTitle: goodsTitle,
			GoodsCover: goodsCover,
			GoodsPrice: float32(goodsPrice),
			GoodsNum:   int64(goodsNum),
			Checked:    int64(checked),
		})
	}
	return
}
